package com.wanshi.servlet;

import com.alibaba.fastjson.JSON;
import com.wanshi.entity.Product;
import com.wanshi.entity.Result;
import com.wanshi.entity.User;
import com.wanshi.service.CartService;
import com.wanshi.utils.Constants;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.Set;

@WebServlet("/cart/totalPrice")
public class totalPrice extends HttpServlet {
    CartService cartService = new CartService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //计算当前用户购物车商品总价
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");

        Map<Product,Integer> map = cartService.findCartByUserId(user.getId()+"");

        Set<Map.Entry<Product, Integer>> entries = map.entrySet();

        double sum = 0;
        for(Map.Entry<Product, Integer> entry:entries){
            Product prod = entry.getKey();
            Integer num = entry.getValue();

            sum += prod.getPrice()*num;
        }

        Result result = new Result();
        result.setCode(Constants.SUCCESS);
        result.setMessage(sum+"");

        response.getWriter().write(JSON.toJSONString(result));

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

